
// 写入日志
const restTool = require('../../middlewares/mysql/mysql');
const until = require('../../middlewares/until');
const methods = {

    /**
     * 添加用户
     * params {userName:"12", password:"sdfqwwed"}
     * */ 
    async addUser (params) {
        const sql = `INSERT INTO user(user_name, password) VALUES ("${params['userName']}","${params['password']}")`;
        const result = await restTool.query(sql, params);
        return result;
    },

    /**
     * 登录
     * params: {user_name:'name': password:"sadfasdf"}
     */ 
    async login (params) {
        const sql = `SELECT * FROM user WHERE user_name="${params['userName']}" AND password="${params['password']}"`;
        console.log(sql)
        const result = await restTool.query(sql, params);
        console.log(result)
        return result;
    },

    /*
    * 更新用户数据
    * params {userId:1, userName:"12", password:"sdfqwwed",token:"ssdfsd"}
    **/ 
    async updateUser (params) {
        let sqlFilter = '';
        if(!params['userId']){
            return -1;
        }
        // 用户名称
        if(params['userName']){
            sqlFilter += ` ${sqlFilter?',':''} user_name='${params['userName']}'`;
        }
        // 用户密码
        if(params['password']){
            sqlFilter += ` ${sqlFilter?',':''} password='${params['password']}'`;
        }
        // 用户token
        if(params['token']){
            sqlFilter += ` ${sqlFilter?',':''} token='${params['token']}'`;
        }

        const sql = `UPDATE user SET ${sqlFilter} WHERE user_id=${params['userId']}`;
        const result = await restTool.query(sql, params);

        return result;
    },

    /**
     * 验证用户登录状态
     * params: {token:"sadflaskdj"}
    */
    async validToken (params) {
        const sql = `SELECT * FROM user WHERE token='${params['token']}'`;
        const result = await restTool.query(sql, params);
        return result;
    }

}
const siteService = {
    async get(type, params) {
        try{
            res = await methods[type](params);
            return res;
        }catch(err){
            console.log(err);
            res = {
                success: false,
                msg: '错误',
                errorCode: 300000
            }
        }
        return res;
    }
}

module.exports = siteService;